import {Component, OnInit, OnDestroy} from '@angular/core';
import {SimpleReuseStrategy} from "./SimpleReuseStrategy";
import {Event, RouterEvent, Router, NavigationEnd} from '@angular/router';
import {filter, takeUntil} from "rxjs/operators";
import {Subject} from 'rxjs';
import {TabService, tabItem} from "./pages/tab.service";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent implements OnInit, OnDestroy {
  destory$ = new Subject();
  tabs: tabItem[] = [
    {
      closed: false,
      name: 'Welcome',
      url: '/welcome'
    }
  ]
  selectedIndex = 0;

  constructor(
    private tabSvr: TabService,
    private router: Router,
  ) {
    this.router.events.pipe(
      takeUntil(this.destory$),
      filter((e: Event): e is RouterEvent => e instanceof NavigationEnd)
    ).subscribe((e: RouterEvent) => {
      // Do something
      const existIndex = this.tabs.findIndex((item) => item.url === e.url);
      if (existIndex !== -1) {
        this.selectedIndex = existIndex;
      } else {
        SimpleReuseStrategy.deleteRouteSnapshot(e.url.replace(/\//g, '_'));
        this.navigate(this.tabs[0].url);
      }
    });
  }

  isCollapsed = false;

  closeTab({index}: { index: number }): void {
    const [{url}] = this.tabs.filter((t, i) => i === index)
    this.selectedIndex = this.tabs.length;
    SimpleReuseStrategy.deleteRouteSnapshot(url.replace(/\//g, '_'));
    this.tabs.splice(index, 1);
    this.navigate(this.tabs[this.tabs.length - 1].url);
  }

  setTab(url: string, name: string): void {
    this.tabSvr.setTab({
      closed: true,
      url,
      name
    });
  }

  navigate(url: string): void {
    this.router.navigate([url]).then();
  }

  ngOnInit() {
    this.tabSvr.getTab().pipe(
      takeUntil(this.destory$)
    ).subscribe((tab: tabItem) => {
      const existIndex = this.tabs.findIndex((item: tabItem) => item.url === tab.url);
      if (existIndex !== -1) {
        this.navigate(this.tabs[existIndex].url);
      } else {
        this.tabs.push(tab);
        this.navigate(this.tabs[this.tabs.length - 1].url);
      }
    });
  }

  ngOnDestroy(): void {
    this.destory$.next();
    this.destory$.complete();
  }

}
